<template>
  <div class="w-full h-full overflow-hidden flex flex-col justify-between p-[15px] box-border">
    <el-tabs v-model="tabActive" type="card">
      <el-tab-pane v-for="item in games" :label="item.Name" :name="item.LotteryId">
        <div class="tab-page-content !py-[15px] !px-[10px] box-border">
          <div class="grow-[1] h-0 overflow-hidden">
            <el-table
              v-loading="state.loading"
              scrollbar-always-on
              :data="state.messages"
              height="100%"
              stripe
              border
              fit
            >
              <el-table-column prop="Key" align="center" label="消息名称" width="200">
                <template #default="{ row }: TableItem">
                  <el-input v-if="row.Custom" v-model="row.Key" placeholder="请输入名称" />
                  <span class="!text-[13px]" v-else>{{ row.Key }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="Content" align="center" label="消息内容">
                <template #default="{ row }: TableItem">
                  <el-input
                    v-model="row.Content"
                    type="textarea"
                    :rows="setRows(row.Key)"
                    resize="none"
                    placeholder="请输入内容"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="消息时间" width="170">
                <template #default="{ row }: TableItem">
                  <div class="flex items-center" v-if="row.TimeEdit == 1">
                    <span class="mr-[10px]">距封盘</span>
                    <el-input-number
                      size="small"
                      class="!w-[60px]"
                      v-model="row.Time"
                      placeholder="时间"
                      :step="1"
                      :min="0"
                      :controls="false"
                    />
                    <span class="ml-[10px]">秒</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="center" label="说明">
                <template #default="{ row }: TableItem">
                  <div
                    class="text-left flex flex-col justify-center"
                    v-if="row.Key == '距封盘N秒喊话'"
                  >
                    <div>{游戏}游戏名称</div>
                    <div>{期号}表示当期期号</div>
                    <div>{second}表示消息时间设置的具体秒</div>
                  </div>
                  <div
                    class="text-left flex flex-col justify-center"
                    v-if="row.Key == '封盘后账单核对消息'"
                  >
                    <div>{核对}以玩家为单位，对订单进行汇总核对</div>
                  </div>
                  <div
                    class="text-left flex flex-col justify-center"
                    v-if="row.Key == '结算后中奖名单'"
                  >
                    <div>{结算} 以玩家为单位，对结算订单展示</div>
                    <div>{中奖名单} 以玩家为单位，对玩家中奖订单展示</div>
                  </div>
                  <div
                    class="text-left flex flex-col justify-center"
                    v-if="row.Key == '结算后玩家积分消息'"
                  >
                    <div>{账单} 以玩家为单位，展示投注玩家的积分情况</div>
                    <div>{玩家数量} 表示有下注的玩家人数</div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="mt-[15px] flex justify-between items-center">
            <div>
              <el-alert
                title="注意：所有花括号（比如{游戏}）包含的都属于系统内置识别码，请不要更改，否则会导致系统无法识别指令。"
                type="warning"
                show-icon
                :closable="false"
              />
            </div>
            <div>
              <el-button
                v-if="premsStore.isEditMessageSetting"
                type="primary"
                @click="handleAllReset"
                >消息重置</el-button
              >
              <el-button
                v-if="premsStore.isEditMessageSetting"
                type="primary"
                :loading="state.updating"
                @click="handleSave"
              >
                保存设置
              </el-button>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script lang="ts" setup>
import { useGameStore } from "@/store/modules/game";
import { cloneDeep, debounce } from "lodash-es";
import { storeToRefs } from "pinia";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { reqMessageShow, reqMessageEdit, reqMessageDefault } from "@/api/setting";
import { usePremsStore } from "@/store/modules/prems";

interface TableItem {
  row: MessageSettingTables;
}
interface State {
  loading: boolean;
  updating: boolean;
  msgId: number;
  messages: MessageSettingTables[];
  cloneMessages: MessageSettingTables[];
}
const premsStore = usePremsStore();
const gameStore = useGameStore();
const { gameTotal } = storeToRefs(gameStore);
const games = computed(() => {
  let list = cloneDeep(gameTotal.value);
  list.sort((a, b) => a.LotterySort - b.LotterySort);
  return list;
});
const tabActive = ref(games.value[0].LotteryId);
const state = reactive<State>({
  loading: false,
  updating: false,
  messages: [],
  msgId: 0,
  cloneMessages: []
});

// 获取消息
const getData = async (LotteryId: number) => {
  try {
    state.loading = true;
    const res = await reqMessageShow(LotteryId);
    state.loading = false;
    state.messages = res.data.Tables;
    state.msgId = res.data.Id;
    state.cloneMessages = cloneDeep(res.data.Tables);
  } catch (error) {
    state.loading = false;
    state.messages = cloneDeep([]);
    console.log(error);
  }
};

const setRows = (key: string) => {
  if (key == "封盘后账单核对消息" || key == "结算后中奖名单" || key == "结算后玩家积分消息") {
    return 6;
  }
  return 4;
};

// 更新消息
const handleSave = debounce(
  async () => {
    if (JSON.stringify(state.messages) == JSON.stringify(state.cloneMessages)) {
      message.warning("暂无修改");
      return;
    }
    try {
      state.updating = true;
      const query = state.messages.map(item => {
        return {
          Content: item.Content,
          Key: item.Key,
          TimeEdit: item.TimeEdit,
          Time: Number(item.Time)
        };
      });
      await reqMessageEdit({
        Id: state.msgId,
        LotteryId: tabActive.value,
        Data: query
      });
      state.updating = false;
      message.success("保存成功");
      getData(tabActive.value);
    } catch (error) {
      state.updating = false;
      console.log(error);
    }
  },
  300,
  { leading: true, trailing: false }
);

// 一键恢复默认
const handleAllReset = () => {
  ElMessageBox.confirm(`确定要恢复到系统初始消息设置吗？`, "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    distinguishCancelAndClose: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true; // 设置 "确定" 按钮加载中
          await reqMessageDefault(tabActive.value);
          message.success("恢复默认成功");
          getData(tabActive.value);
          instance.confirmButtonLoading = false;
          done(); // 操作成功后关闭对话框
        } catch (error) {
          done();
          console.error("操作失败", error);
          instance.confirmButtonLoading = false; // 如果失败，取消加载状态
        }
      } else {
        done(); // 取消时直接关闭
      }
    }
  });
};

watch(
  () => tabActive.value,
  val => {
    nextTick(() => {
      getData(val);
    });
  }
);
onMounted(() => {
  getData(tabActive.value);
});
</script>
<style lang="scss" scoped>
:deep() {
  .el-input,
  .el-textarea,
  .el-select {
    --el-input-bg-color: #f9f9f9;
    --el-fill-color-blank: #f9f9f9;
  }
}
</style>
